class Router {
  constructor(routes) {
    this.routes = routes;
    this.currentRoute = null;
    this.beforeHooks = [];
    this.afterHooks = [];
    window.addEventListener('popstate', this.handlePopState.bind(this));
  }

  handlePopState() {
    this.resolve(window.location.pathname);
  }

  resolve(path) {
    this.currentRoute = this.routes.find(route => route.path === path);
    if (this.currentRoute) {
      this.currentRoute.component.mount();
    }
  }

  async push(path) {
    const to = this.routes.find(route => route.path === path);
    const from = this.currentRoute;

    for (const hook of this.beforeHooks) {
      await hook(to, from);
    }

    window.history.pushState(null, '', path);
    this.resolve(path);

    for (const hook of this.afterHooks) {
      hook(to, from);
    }
  }

  beforeEach(hook) {
    this.beforeHooks.push(hook);
  }

  afterEach(hook) {
    this.afterHooks.push(hook);
  }
}

export { Router };